package neu.edu.cn.nuemall.config;

import neu.edu.cn.nuemall.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 对SpringSecurity安全认证的配置
 *
 * @author lemonit.cn-liuri
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    private UserinfoService userinfoService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 此行为了解决security默认不运行页面被嵌入iframe
                .headers().frameOptions().disable().and()
                // 放开第三方库 样式 图片 和js库的权限校验
                .authorizeHttpRequests()
                .antMatchers("/libs/**", "/styles/**", "/javascript/**", "/images/**", "/res/**","/img/**").permitAll()
                .antMatchers("/", "/edge/**","/admin/**").permitAll()
                .anyRequest()
                .authenticated()
                // 自定义登录页面的字段
                .and()
                .formLogin()
                .loginPage("/edge/login")
                .loginProcessingUrl("/edge/handler/login")
                .usernameParameter("name")
                .passwordParameter("password")
                .defaultSuccessUrl("/")
                .permitAll()
                // 配置退出登录
                .and()
                .logout()
                .logoutUrl("/edge/logout")
                .logoutSuccessUrl("/")

                .and()
                .csrf()
                .disable();
        ;
        return http.build();
    }

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userinfoService).passwordEncoder(new SecurityPasswordEncoder());
    }
}
